package cookie;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Create By IntelliJ IDEA
 *
 * @Author: jsonor
 * @Create-Time: 2017/10/10 8:29
 * @Description: 用于验证用户输入的数据是否正确
 */
@WebServlet(name = "check", urlPatterns = {"/check"})
public class CheckServlet extends HttpServlet {

  private static final String USER_NAME = "abc";
  private static final String PASS_WORD = "abc123";

  @Override
  protected void doGet(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException {

    String username = (String) request.getAttribute("username");
    String password = (String) request.getAttribute("password");
    // 这里假装连接了数据库进行查询
    // ....
    if (!USER_NAME.equals(username) ||
        !PASS_WORD.equals(password)) {
      response.sendRedirect("/cookie/error.html");
    } else {
      Cookie ckUsername = new Cookie("username", username);
      Cookie ckPassword = new Cookie("password", password);
      ckUsername.setMaxAge(3600);
      ckPassword.setMaxAge(3600);
      response.addCookie(ckPassword);
      response.addCookie(ckUsername);
      response.sendRedirect("/cookie/index.html");
    }
  }
}
